package com.joseph.controller;

import java.util.List;

import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.beans.DocumentObjectBinder;
import org.apache.solr.client.solrj.impl.HttpSolrServer;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.common.SolrDocumentList;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.joseph.base.BaseController;
import com.joseph.model.Product;

/**
 * @description 
 * @author Joseph_Mok
 * @date 2016年1月20日下午3:01:39
 */

@Controller
public class SearchController extends BaseController {

	@RequestMapping(value="/search")
	public void search(@RequestParam String text) throws SolrServerException {
	    HttpSolrServer server = new HttpSolrServer(SOLR_URL);
	    server.setMaxRetries(1);
	    server.setConnectionTimeout(5000); 

	    SolrQuery query = new SolrQuery();
	    query.set("q",text);
	    query.setStart(0);
	    query.setRows(2);
	    //query.setFacet(true);
	    //query.addFacetField("author_s"); 面包屑

	    QueryResponse response = server.query(query);
	    // 搜索得到的结果数
	    System.out.println("Find:" + response.getResults().getNumFound());
	    // 输出结果
	    
	    SolrDocumentList list = response.getResults();
	    
	    DocumentObjectBinder binder = new DocumentObjectBinder();
	    List <Product> beanList = binder.getBeans(Product.class, list);
	    for(Product news : beanList){
	      System.out.println(news.getId());
	    }
	}
	
	@RequestMapping(value="/suggest")
	@ResponseBody
	public Object suggestion(@RequestParam String text) throws SolrServerException {
	    HttpSolrServer server = new HttpSolrServer(SOLR_URL);
	    server.setMaxRetries(1);
	    server.setConnectionTimeout(5000); 

	    SolrQuery query = new SolrQuery();
	    query.set("q", text);//查询的词 
        query.set("qt", "/suggest");//请求到suggest中 
	    QueryResponse response = server.query(query);

	    // 搜索得到的结果数
	    //System.out.println("Find:" + response.getResults().getNumFound());
	    // 输出结果
	    return response.getSpellCheckResponse().getSuggestions();
	  }
}
